# _*_ coding: utf-8 _*_
# @Time : 2020/10/22 10:39
# @Author : liupengfei
# @File : serializers.py

from rest_framework import serializers
from apps.system.models import Area
from apps.system.serializers import UploadSerializer
from .models import Store, Coupon, FocusStore


class StoreDetailSerializer(serializers.ModelSerializer):
    thumbnail = serializers.SerializerMethodField()
    is_focus = serializers.SerializerMethodField()

    def get_is_focus(self, obj):
        store_focus = FocusStore.objects.filter(store=obj, member=self.context['request'].user.member)
        if store_focus:
            return True
        return False

    def get_thumbnail(self, obj):
        return UploadSerializer(obj.thumbnail).data if obj.thumbnail else ''

    class Meta:
        model = Store
        fields = ('id', 'thumbnail', 'city', 'is_focus', 'describe', 'name', 'address',
                  'address_detail', 'latitude', 'longitude')


class StoreCudSerializer(serializers.ModelSerializer):
    class Meta:
        model = Store
        fields = '__all__'

    def create(self, validated_data):
        # print(self.initial_data)
        city_name = self.initial_data['city_name']
        member = self.context['request'].user.member
        city = Area.objects.filter(name__icontains=city_name, level=Area.CITY).first()
        if not city and member.city:
            city = Area.objects.filter(name__icontains=member.city, level=Area.CITY).first()

        validated_data['merchant'] = member
        validated_data['city'] = city
        instance = super(StoreCudSerializer, self).create(validated_data)

        return instance


class CouponSerializers(serializers.ModelSerializer):
    status_text = serializers.CharField(source='get_status_display', read_only=True)
    value_type_text = serializers.CharField(source='get_value_type_display', read_only=True)

    class Meta:
        model = Coupon
        fields = (
            'title', 'status_text', 'status', 'value_type', 'value_type_text', 'value', 'notes', 'take_effect_time',
            'lose_efficacy_time')
